package com.data;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;


public class DataManager {

	public DataManager (Context ctx) {
		this.context = ctx;
	}
	
	/**
     * Open the database. If it cannot be opened, try to create a new
     * instance of the database. If it cannot be created, throw an exception to
     * signal the failure
     * @return this (self reference, allowing this to be chained in an initialization call)
     * @throws SQLException if the database could be neither opened or created
     */
    public DataManager open() throws SQLException {
        dbHelper = new DatabaseHelper(context);
        database = dbHelper.getWritableDatabase();
        return this;
    }
    
    /**
     * Close the database.
     * */
    public void close() {
        dbHelper.close();
    }


    /**
     * Creates a new entry in the application database.
     */
    public long createNewEntry(String value, String date, String time) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_VALUE, value);
        initialValues.put(KEY_DATE, date);
        initialValues.put(KEY_TIME, time);
        return database.insert(DATABASE_TABLE, null, initialValues);
    }

    /**
     * Delete the database entry with the given id.
     * 
     * @param rowId id
     * @return true if deleted, false otherwise
     */
    public boolean deleteEntry(long rowId) {
        return database.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
    }

    /**
     * Return a Cursor over the list.
     * @return Cursor
     */
    public Cursor fetchAllEntries() {

        return database.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_VALUE, KEY_DATE, KEY_TIME}, null, null, null, null, null);
    }

    /**
     * Return a Cursor positioned at the table entry that matches the given rowId
     * @param rowId id
     * @return Cursor positioned to matching table entry, if found
     * @throws SQLException if the id could not be found/retrieved
     */
    public Cursor fetchEntry(long rowId) throws SQLException {
        Cursor mCursor = database.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
                		KEY_VALUE, KEY_DATE, KEY_TIME}, KEY_ROWID + "=" + rowId,
                		null, null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }

    /**
     * Update the table entry using the details provided.
     * @param rowId id
     * @param value
     * @param date
     * @param time
     * @return true if the entry was successfully updated, false otherwise
     */
    public boolean updateEntry(long rowId, String value, String date, String time) {
        ContentValues args = new ContentValues();
        args.put(KEY_VALUE, value);
        args.put(KEY_DATE, date);
        args.put(KEY_TIME, time);
        return database.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
    }
	
    // columns titles.
	public static final String KEY_VALUE = "value";
    public static final String KEY_DATE = "date";
    public static final String KEY_TIME = "time";
    public static final String KEY_ROWID = "_id";

    // database components.
    private static final String TAG = "DataManager";
    private DatabaseHelper dbHelper;
    private SQLiteDatabase database;
    
    // database constants.
    private static final String DATABASE_CREATE = "create table weights (_id integer primary key autoincrement, " + "value text not null, date text not null, time text not null);";
    private static final String DATABASE_NAME = "data";
    private static final String DATABASE_TABLE = "weights";
    private static final int DATABASE_VERSION = 2;

    private final Context context;
    
    // Inner class created as static to avoid creating a reference to it.
    /**
     * A DatabaseHelper is a component that gives some trivial functionality (related with a database)
     * like onCreate(), onUpgrade(), etc. It extends from SQLiteOpenHelper. 
     * @see SQLiteOpenHelper.
     *  
     **/
    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

       @Override
        public void onCreate(SQLiteDatabase db) {
        	// Execute sql command to create the database.
            db.execSQL(DATABASE_CREATE);
        }

        
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS weights");
            onCreate(db);
        }
        
        
        @Override
        public SQLiteDatabase getWritableDatabase() {
        	return super.getWritableDatabase();
        }
    }
}
